package com.yups.web;
import com.yups.model.Carousels;
import com.yups.model.Service;
import com.yups.service.CarouselsService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 轮播图服务类
 *
 * @author 于鹏生
 */
@WebServlet(urlPatterns = "/servlet/CarouselsAction")
public class CarouselsAction extends HttpServlet {
	private CarouselsService carouselsService = new CarouselsService();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String act = request.getParameter("act");
		if (act == null) {
			act = "list";
		}
		Carousels carousels = getCarouselsByRequest(request);
		switch (act) {
			case "add":
				request.setAttribute("services",carouselsService.getServices());
				forward(request, response, "act", "addSave",
						"../WEB-INF/jsp/carousels/input.jsp");
				break;
			case "delete"://1参 id
				forward(request, response, carouselsService.deleteCarousels(carousels) ?
						"删除成功" : "删除失败", "CarouselsAction?act=list");
				break;
			case "update"://1参 id
				Carousels carousels1 = carouselsService.getCarousels(carousels);
				request.setAttribute("services",carouselsService.getServices());
				request.setAttribute("carousels", carousels1);
				forward(request, response, "act",
						"updateSave", "../WEB-INF/jsp/carousels/input.jsp");
				break;
			default:
				forward(request, response, "carouselses",
						carouselsService.getCarouselses(),
						"../WEB-INF/jsp/carousels/list.jsp");
		}
	}

	private void forward(HttpServletRequest request, HttpServletResponse response,
						 String msg, String url) throws ServletException, IOException {
		request.setAttribute("msg",msg);
		request.getRequestDispatcher(url).forward(request,response);
	}

	private void forward(HttpServletRequest request, HttpServletResponse response,
						 String key, Object value, String url)
			throws ServletException, IOException {
		request.setAttribute(key,value);
		request.getRequestDispatcher(url).forward(request,response);
	}

	private Carousels getCarouselsByRequest(HttpServletRequest request) {
		Carousels carousels = new Carousels();
		String id = request.getParameter("id");
		if (id != null && id.matches("\\d{1,9}")) {
			carousels.setId(Integer.parseInt(id));
		}
		carousels.setIcon(request.getParameter("icon"));
		String serviceId = request.getParameter("serviceId");
		if (serviceId != null && serviceId.matches("\\d{1,9}")) {
			carousels.setService(new Service(Integer.parseInt(serviceId)));
		}
		return carousels;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
